package com.niodata.dp.monitor.core.task.util;

import freemarker.cache.StringTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import java.io.IOException;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by admin on 2018/5/16.
 */
public class TemplateUtil {

  public static final String TEM_NOT_FOUND = "NOT_FOUND";
  public static final String TEM_ALERT_COMMON = "ALERT_COMMON";
  public static final String TEM_TIME_OUT = "TIME_OUT";
  public static final String TEM_START = "START";
  private static final String NOT_FOUND = "任务名称：${taskName} \\n\\n任务状态：${status} "
        + "\\n\\n任务链接：${msg}\\n\\n预期执行时间：${expectTime}\\n\\n所属组：${groupName}\\n";
  private static final String ALERT_COMMON = "任务名称：${taskName} \\n\\n任务状态：${status} "
        + "\\n\\n任务链接：${msg}\\n\\n执行ID：${execId}\\n\\n所属组：${groupName}\\n";
  private static final String TIME_OUT = "任务名称：${taskName} \\n\\n任务状态：${status} "
        + "\\n\\n任务链接：${msg}\\n\\n执行ID：${execId}\\n\\n设置超时时间：${expectTime} 分钟"
        + "\\n\\n已执行时间：${runningTime} 分钟\\n\\n所属组：${groupName}\\n";
  private static final String START = "任务名称：${taskName} \\n\\n任务状态：${status} "
        + "\\n\\n任务链接：${msg}\\n\\n执行ID：${execId}\\n\\n开始时间：${startTime}\\n\\n所属组：${groupName}\\n";
  private static Map<String, String> templateMap;
  private static Configuration cfg = new Configuration(Configuration.VERSION_2_3_23);

  static {
    templateMap = new HashMap<>();

    try {
      cfg = new Configuration(Configuration.VERSION_2_3_23);
      cfg.setDefaultEncoding("UTF-8");
      StringTemplateLoader stringLoader = new StringTemplateLoader();
      stringLoader.putTemplate(TEM_NOT_FOUND, NOT_FOUND);
      stringLoader.putTemplate(TEM_ALERT_COMMON, ALERT_COMMON);
      stringLoader.putTemplate(TEM_TIME_OUT, TIME_OUT);
      stringLoader.putTemplate(TEM_START, START);
      cfg.setTemplateLoader(stringLoader);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  public static String genAlertMsgByTemplate(String templateKey, Map<Object, Object> data)
        throws IOException, TemplateException {
    Template template = cfg.getTemplate(templateKey);
    StringWriter writer = new StringWriter();
    template.process(data, writer);
    String msg = writer.toString();
    writer.close();
    return msg;
  }

}